package cn.net.mugui.net.p2p;

import java.net.DatagramSocket;

import com.mugui.base.base.Autowired;
import com.mugui.base.base.Component;

import cn.net.mugui.net.key.utils.Base58;
import cn.net.mugui.net.udp.UdpBag;
import cn.net.mugui.net.udp.UdpServer;
import cn.net.mugui.net.udp.UdpServer.ReceiveListener;

@Component
public class UdpBagHandle implements ReceiveListener {
	
	@Autowired
	private  DefaultFuncHandle funcHandle;

	@Autowired
	private ServerManager manager;
    @Override
    public boolean ping(DatagramSocket socket, UdpServer server, UdpBag resolve) {
    	ServerAttr serverAttr = new ServerAttr();
		serverAttr.setAddress(Base58.encode(resolve.getFrom()));
		ServerAttr serverAttr2 = manager.get(serverAttr.getAddress());
		if (serverAttr2 == null) {
			serverAttr.setHost(server.getTo_host()).setPort(server.getTo_port());
			serverAttr.setName("");
			serverAttr.setStatus(ServerAttr.status_3);
			if(serverAttr.getType()==null)
			serverAttr.setType(ServerAttr.type_0);
			manager.add(serverAttr.getAddress(), serverAttr);
			funcHandle.doP2P("ping.method.add",socket,server,resolve, null);
		} else {
			serverAttr = serverAttr2;
			serverAttr.setHost(server.getTo_host()).setPort(server.getTo_port());
			serverAttr.setName("");
			serverAttr.setStatus(ServerAttr.status_3);
			if(serverAttr.getType()==null)
			serverAttr.setType(ServerAttr.type_0);
			funcHandle.doP2P("ping.method.update",socket,server,resolve, null);
		}
        return true;
    }

    @Override
    public boolean retPing(DatagramSocket socket,UdpServer server, UdpBag resolve) {
		funcHandle.doP2P("retPing",socket,server,resolve, null);//TODO ret_ping消息暂时无需处理
		return false;
    }

	@Autowired
	private Server server;

    @Override
	public boolean sucess(DatagramSocket socket, UdpServer udpServer, UdpBag resolve) {
		if (resolve.getBag_type() == UdpBag.bag_type_1) {// 是一个广播型消息，将消息转发给所有可以沟通的人
			server.broadcast(resolve);
		}
		funcHandle.doP2P("sucess", socket, udpServer, resolve, null);
        return true;
    }



}
